﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using dal;
using entity;
using System.Text;
using System.Text.RegularExpressions;
using cmsservice.DAL;
/// <summary>
///NewsBLL 的摘要说明
/// </summary>
public class NewsBLL
{
	public NewsBLL()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    public string GetByIdStr(long id)
    {
        string key = "news:" + id.ToString();
        string str = (string)MemcachedTools.Get(key);
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        NewsEntity c = null;
        CMSEntities cms = new CMSEntities();
        var lst = cms.News.Where(x => x.id == id).ToArray();
        if (lst.Length == 0)
        {
            return null;
        }
        else
        {
            c = new NewsEntity();
            var temp = lst[0];
            c.Author = temp.author;
            c.Content = temp.content;
            c.Id = temp.id;
            c.KeyWord = temp.keyword;
            c.PTime = temp.ptime;
            c.Source = temp.Source;
            c.Stcok = temp.Stock;
            c.Title = temp.title;
            c.Summary = temp.Summary;
            c.ImageUrl = temp.ImageUrl;
            c.Url = temp.OutsideUrl;
        }
        str = JsonBLL.ToJson(c);
        MemcachedTools.Add(key, str, DateTime.Now.AddHours(24));
        return str;
    }

    public NewsEntity GetById(long id)
    {
        string str = GetByIdStr(id);
        if (string.IsNullOrEmpty(str))
        {
            return null;
        }
        else
        {
            return JsonBLL.ToObject<NewsEntity>(str);
        }
    }

    /// <summary>
    /// 得到新闻内容
    /// 添加了股票标签
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public string GetById2(long id)
    {
        string key = "news_stock:" + id.ToString();
        string str = (string)MemcachedTools.Get(key);
        NewsEntity c = null;
        if (!string.IsNullOrEmpty(str))
        {
            return str;
        }
        var news = GetById(id);
        news.Content = Regex.Replace(news.Content, "<span ca=\"true\"[^>]*>", "<span>");
        news.Content = ReplaceGP(news.Content);
        str = JsonBLL.ToJson(news);
        MemcachedTools.Add(key,  str, DateTime.Now.AddHours(24));
        return str;
    }

    static string CapCode(Match m)
    {
        CommonBLL cbll = new CommonBLL();
        // Get the matched string.
        string x = m.ToString();
        x = x.Substring(1, 6);
        string pre = m.Value.Substring(0, 1);
        var dic=cbll.Dic证券列表;
        if (dic.ContainsKey(x))
        {
            var c = dic[x];
            return pre+"<span ca=\"true\" t=\"" + c.F + "\" c=\"" + c.C + "\">" + x + "</span>";
        }
        else
        {
            return m.Value;
        }
    }

    static string CapName(Match m)
    {
        CommonBLL cbll = new CommonBLL();
        // Get the matched string.
        string x = m.ToString();
        var dic = cbll.Dic证券列表;
        if (dic.ContainsKey(x))
        {
            var c = dic[x];
            return "<span ca=\"true\" t=\"" + c.F + "\" c=\"" + c.C + "\">" + x + "</span>";
        }
        else
        {
            return m.Value;
        }
    }

    private Regex SbCodeReg
    {
        get
        {
            string key = "NewsBLL_ReplaceGP_sbCodeReg";
            Regex sbCodeReg = (Regex)System.Web.HttpContext.Current.Cache[key];
            if (sbCodeReg!=null)
                return sbCodeReg;
            StringBuilder sb = new StringBuilder();
            CommonBLL cbll = new CommonBLL();
            var lst = cbll.Get证券列表();
            var tem = lst.Where(x => x.C.Length < 6).ToArray();
            foreach (TempStock stock in lst)
            {
                try
                {
                    string sName = stock.N;
                    string code = stock.C;
                    string f = stock.F;
                    if (code.Length != 6)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(sName))
                    {
                        continue;
                    }
                    sb.Append("[^#]").Append(code).Append("|");
                }
                catch
                {

                }
            }
            sb = sb.Remove(sb.Length - 1, 1);
            string str=sb.ToString();
            Regex reg = new Regex(str);
            System.Web.HttpContext.Current.Cache.Add(key, reg, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
            return reg;
        }
    }

    private Regex SbNameReg
    {
        get
        {
            string key = "NewsBLL_ReplaceGP_sbNameReg";
            Regex sbCodeReg = (Regex)System.Web.HttpContext.Current.Cache[key];
            if (sbCodeReg!=null)
                return sbCodeReg;
            StringBuilder sb = new StringBuilder();
            CommonBLL cbll = new CommonBLL();
            var lst = cbll.Get证券列表();
            var tem = lst.Where(x => x.C.Length < 6).ToArray();
            foreach (TempStock stock in lst)
            {
                try
                {
                    string sName = stock.N;
                    string code = stock.C;
                    string f = stock.F;
                    if (code.Length != 6)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(sName))
                    {
                        continue;
                    }
                    sb.Append(sName.Replace("*", "\\*")).Append("|");
                }
                catch
                {

                }
            }
            sb = sb.Remove(sb.Length - 1, 1);
            string str = sb.ToString();
            Regex reg = new Regex(str);
            System.Web.HttpContext.Current.Cache.Add(key, reg, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
            return reg;
        }
    }

    public string ReplaceGP(string str)
    {
        str= SbCodeReg.Replace(str, CapCode);
        str = SbNameReg.Replace(str, CapName);
        return str;
    }

    public List<NewsList> GetNewsListByStock(string stock,int top)
    {
        string key = "NewsBLL_GetNewsListByStock_" + stock + "_" + top ;

        var lst = (List<NewsList>)System.Web.HttpContext.Current.Cache[key];
        if (lst != null)
        {
            return lst;
        }

        dal.CMSEntities dal = new dal.CMSEntities();
        var data = from a in dal.NewsRelatedStocks
                   from b in dal.News
                   from c in dal.News_Type
                   where  a.Stock == stock && a.NewsId == b.id && b.id == c.NewsId && b.IsEnable == true && b.ptime <= DateTime.Now
                   orderby b.ptime descending
                   select new entity.NewsList { Id = b.id, Source = b.Source, PTime = b.ptime, Step = b.step, Title = b.title, Url = b.OutsideUrl };
        data = data.Take(top);
        lst = data.ToList();
        if (lst != null && lst.Count > 0)
        {
            System.Web.HttpContext.Current.Cache.Add(key, lst, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
        }
        return lst;
    }

}